package cn.iocoder.devlop.module.annual.report.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.devlop.module.infra.util.ConfigUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import static cn.hutool.crypto.SecureUtil.md5;
import static cn.iocoder.devlop.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.devlop.module.annual.report.enums.ErrorCodeConstants.SMS_DO_NOT_SEND;

@Slf4j
public class SmsApi {

    public static void sendSmsApiMessage(String phone, String code) {
        Long timestamp = DateUtil.currentSeconds();
        String smsTemplate = ConfigUtils.getConfigByKey("sms");
        String time = ConfigUtils.getConfigByKey("sms_expiration_time");
//        // 检查能否发短信
        String endNumber = StringUtils.right(phone, 4);
        String content = String.format(smsTemplate, endNumber, code, time);
        String accountId = "nxxzspj";
        String password = "nxxzspj2020";
        String productId = "1012808";
        String url = "https://api.51welink.com/EncryptionSubmit/SendSms.ashx";
        long random = RandomUtil.randomLong(1, Integer.MAX_VALUE);
        JSONObject body = JSONUtil.createObj()
                .set("AccountId", accountId)
                .set("ExtendNo", "")
                .set("ProductId", productId)
                .set("PhoneNos", phone)
                .set("Content", content)
                .set("AccessKey", calcSendSmsSign(accountId, phone, password, random, timestamp))
                .set("Timestamp", timestamp)
                .set("Random", random)
                .set("OutId", "")
                .set("SendTime", "");
        HttpRequest request = HttpRequest.post(url)
                .contentType("application/json")
                .timeout(60 * 1000)
                .body(body.toString());
        int i = 3;
        do{
            HttpResponse response = request.execute();
            if (HttpStatus.HTTP_OK != response.getStatus()) {
                log.error("status:{} error:{}",response.getStatus(),response.body());
                i--;
            }else{
                return;
            }
        }while (i>0);
        throw exception(SMS_DO_NOT_SEND);
    }

    public static String calcSendSmsSign(String accountId, String mobile, String password, long random, long timestamp) {
        StringBuilder builder = new StringBuilder("AccountId=")
                .append(accountId)
                .append("&PhoneNos=")
                .append(mobile)
                .append("&Password=")
                .append(md5(password + "SMmsEncryptKey").toUpperCase())
                .append("&Random=")
                .append(random)
                .append("&Timestamp=")
                .append(timestamp);

        return DigestUtils.sha256Hex(builder.toString());
    }

}
